// src/utils/testOssApi.js - OSS接口测试工具

import { torrents } from '../services';

/**
 * 测试OSS get_torrent接口
 */
export const testGetAllTorrents = async () => {
  console.log('🧪 开始测试 OSS get_torrent 接口...');

  try {
    const startTime = Date.now();
    const response = await torrents.getAllUploadedTorrents();
    const endTime = Date.now();

    console.log(`⏱️  请求耗时: ${endTime - startTime}ms`);

    if (response.success) {
      console.log('✅ 接口调用成功!');
      console.log('📊 响应数据:', {
        种子数量: response.data.total || 0,
        数据类型: Array.isArray(response.data.torrents) ? 'Array' : typeof response.data.torrents,
        第一个种子: response.data.torrents?.[0] || null
      });

      // 详细分析种子数据结构
      if (response.data.torrents && response.data.torrents.length > 0) {
        const firstTorrent = response.data.torrents[0];
        console.log('🔍 第一个种子的数据结构:', Object.keys(firstTorrent));
        console.log('📝 种子详情:', firstTorrent);
      }

      return {
        success: true,
        data: response.data,
        responseTime: endTime - startTime
      };
    } else {
      console.log('❌ 接口调用失败:', response.message);
      return {
        success: false,
        error: response.message,
        responseTime: endTime - startTime
      };
    }
  } catch (error) {
    console.log('💥 接口调用异常:', error);
    return {
      success: false,
      error: error.message,
      responseTime: null
    };
  }
};

/**
 * 比较OSS接口和localStorage数据
 */
export const compareDataSources = async () => {
  console.log('🔄 比较OSS接口和localStorage数据...');

  try {
    // 获取OSS数据
    const ossResponse = await torrents.getAllUploadedTorrents();

    // 获取localStorage数据
    const localResponse = await torrents.getTorrents();

    console.log('📊 数据对比结果:');
    console.log('- OSS接口种子数:', ossResponse.data?.total || 0);
    console.log('- localStorage种子数:', localResponse.data?.torrents?.length || 0);

    if (ossResponse.success && ossResponse.data.torrents.length > 0) {
      console.log('🌐 OSS数据字段:', Object.keys(ossResponse.data.torrents[0]));
    }

    if (localResponse.success && localResponse.data.torrents.length > 0) {
      console.log('💾 localStorage数据字段:', Object.keys(localResponse.data.torrents[0]));
    }

    return {
      oss: ossResponse.data,
      local: localResponse.data
    };
  } catch (error) {
    console.log('❌ 数据对比失败:', error);
    return null;
  }
};

/**
 * 完整的API测试套件
 */
export const runApiTests = async () => {
  console.log('🚀 开始运行完整的API测试套件...');
  console.log('=====================================');

  // 测试1: OSS接口基本功能
  console.log('\n📝 测试1: OSS接口基本功能');
  const test1 = await testGetAllTorrents();

  // 测试2: 数据源对比
  console.log('\n📝 测试2: 数据源对比');
  const test2 = await compareDataSources();

  // 测试3: 错误处理
  console.log('\n📝 测试3: 错误处理');
  try {
    // 模拟网络错误
    const originalFetch = window.fetch;
    window.fetch = () => Promise.reject(new Error('模拟网络错误'));

    const errorResponse = await torrents.getAllUploadedTorrents();
    console.log('🛡️  错误处理结果:', errorResponse.success ? '成功回退到本地存储' : '错误处理失败');

    // 恢复原始fetch
    window.fetch = originalFetch;
  } catch (error) {
    console.log('💥 错误处理测试失败:', error);
  }

  console.log('\n=====================================');
  console.log('🏁 API测试套件执行完成');

  return {
    ossTest: test1,
    compareTest: test2
  };
};

// 在开发环境下自动运行测试
if (process.env.NODE_ENV === 'development') {
  // 延迟执行，确保应用启动完成
  setTimeout(() => {
    if (window.location.search.includes('test=oss')) {
      runApiTests();
    }
  }, 3000);
}

export default {
  testGetAllTorrents,
  compareDataSources,
  runApiTests
}; 